# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

"""Resource loading and handling module"""
from __future__ import division, absolute_import
import os, fnmatch, hashlib
import pyglet
from src import conf

images = {}
resid_map = {}

def translate_path(path):
    """translate the internal path to os path"""
    return os.path.join(conf.data_path, *path.split('/'))

def add_image(name, img):
    print 'loaded image!!!!!!!!!!!!!!!', name
    global images, resid_map
    images[name] = img
    resid_map[to_resid(img)] = img

def to_resid(img):
    # fixme: using image hash is weak, need more robust solution
    rawimage = img.get_image_data()
    format = 'RGBA'
    pitch = rawimage.width * len(format)
    pixels = rawimage.get_data(format, pitch)
    return hashlib.md5(pixels).hexdigest()

def from_resid(id):
    return resid_map[id]

def load(path):
    path = translate_path(path)
    if fnmatch.fnmatch(path, '*.png'):
        return pyglet.image.load(path)
    elif fnmatch.fnmatch(path, '*.wav'):
        return pyglet.media.load(path, streaming=False)
    else:
        raise NotImplementedError

def list(path, basename=False):
    """similar to famous `ls` command but returns the internal paths"""
    filter_pat = '*'
    if '*' in path: # fixme
        idx = path.index('*')
        path, filter_pat = path[:idx], path[idx:] 
    path = path.rstrip('/')
    ospath = translate_path(path) 
    return map(lambda x: path + '/' + x, fnmatch.filter(os.listdir(ospath), filter_pat))
     
